package com.googlecode.eventio.internal;

import java.util.HashSet;
import java.util.Set;

import com.googlecode.eventio.Reaction;

public class Latch {

	private final Set<DirectHolder> tracked = new HashSet<DirectHolder>();

	private Runnable completionTask;

	public <T> Reaction<T> track(final Reaction<T> reaction) {
		final DirectHolder holder = new DirectHolder(reaction);
		tracked.add(holder);
		return new Reaction<T>() {
			@Override
			public void react(T input) {
				try {
					reaction.react(input);
				} finally {
					tracked.remove(holder);
					if (tracked.isEmpty()) {
						completionTask.run();
					}
				}
			};
		};
	}

	public <T> void onComplete(Runnable task) {
		completionTask = task;
	}

	private static class DirectHolder {
		final Reaction r;

		public DirectHolder(Reaction r) {
			super();
			this.r = r;
		}

	}

}
